package com.ajaxjs.cms.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.mvc.annotation.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;

import com.ajaxjs.cms.model.Article;
import com.ajaxjs.cms.service.ArticleService;
import com.ajaxjs.config.ConfigService;
import com.ajaxjs.framework.model.ModelAndView;
import com.ajaxjs.mvc.controller.CommonController;
import com.ajaxjs.util.StringUtil;
import com.ajaxjs.util.logger.LogHelper;
import com.ajaxjs.web.HtmlHead;
import com.ajaxjs.web.upload.Upload;
import com.ajaxjs.web.upload.UploadException;
import com.ajaxjs.web.upload.UploadRequest;


/**
 * just a json
 * 
 * @author xinzhang
 *
 */
@Controller
@Path("/admin/article")
public class ArticleAdminController extends CommonController<Article, Long> {
	private static final LogHelper LOGGER = LogHelper.getLog(ArticleAdminController.class);
	
	public ArticleAdminController() {
		setAdminUI(true);
	}

	@Override
	public ArticleService getService() {
		// 单例
		/*
		 * if(super.getService() == null) setService(new ArticleAdminService());
		 * return (ArticleAdminService) super.getService();
		 */

		return new ArticleService();
	}

	@GET
	@Path("list")
	public String list(@QueryParam("start") int start, @QueryParam("limit") int limit, ModelAndView model) {
		CatalogController.initCatalog(ConfigService.getValueAsInt("data.newsCatalog_Id"), model, true);
		
		return super.list(start, limit, model);
	}

	/**
	 * 新建
	 */
	@GET
	@Override
	public String createUI(ModelAndView model) {
		CatalogController.initCatalog(ConfigService.getValueAsInt("data.newsCatalog_Id"), model);

		return super.createUI(model);
	}

	@POST
	@Override
	public String create(Article news, ModelAndView model) {
		return super.create(news, model);
	}

	/**
	 * 编辑
	 */
	@GET
	@Path("{id}")
	@Override
	public String info(@PathParam("id") Long id, ModelAndView model) {
		LOGGER.info("后台管理-修改 UI");
		model.put("isCreate", false);

		CatalogController.initCatalog(ConfigService.getValueAsInt("data.newsCatalog_Id"), model);

		return super.info(id, model);
	}

	@PUT
	@Path("{id}")
	@Override
	public String update(Article news, ModelAndView model) {
		return super.update(news, model);
	}

	@DELETE
	@Path("{id}")
	public String delete(@PathParam("id") Long id, ModelAndView model) {
		Article news = new Article(); // 删除比较特殊
		news.setId(id);
		return delete(news, model);
	}

	@POST
	@Path("setStatus/{id}")
	public String setStatus(@PathParam("id") Long id, Article news, ModelAndView model) {
		news.setId(id);
		System.out.println(news.getStatus());
		return "";
	}
	
	@POST
	@Path("uploadImg")
	public String uploadImg(HttpServletRequest request) {
		UploadRequest ur = new UploadRequest();
		System.out.println("images" + File.separatorChar);
		ur.setUpload_save_folder(HtmlHead.Mappath(request.getServletContext(), "images") + File.separatorChar);// 指定保存目录
		ur.setRequest(request);

		try {
			new Upload().upload(ur);
		} catch (UploadException e) {
			return String.format(json_not_ok, e.getMessage());
		}

		if (!ur.isOk()) {
			return json_not_ok_simple;
		}

		LOGGER.info("上传头像成功！" + ur.getUploaded_save_filePath());
		
		String perfix = HtmlHead.getBasePath(request); // 拼凑 url 前缀
		return String.format(upload_avatar_ok, "admin", "修改头像成功！", perfix + upload_avatar_folder + ur.getUploaded_save_fileName());
	}
	
	private final static String upload_avatar_folder = "/images/";
	private final static String upload_avatar_ok = "json::{\"isOk\": true, \"msg\" : \"用户 id：%s %s\", \"url\": \"%s\"}";
	
	@GET
	@Path("gallery")
	public String gallery(HttpServletRequest request) {
		String folder = HtmlHead.Mappath(request, "/images");
		
		File[] files = new File(folder).listFiles();
		if (files == null)
			return null;
		
		List<String> filenames = new ArrayList<>();

		for(File file : files) {
			if (!file.isDirectory()) {
				String fileName = file.getName();
				if (fileName.contains(".jpg") || fileName.contains(".gif") || fileName.contains(".png")) 
					filenames.add("\"" + fileName + "\"");
			}
		}
		
		String json = "json::[" + StringUtil.stringJoin(filenames, ",") + "]";
		return json;
	}
}
